package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.entity.UserVisitor;
import com.yuelao.yuelao_backend.mapper.UserVisitorMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.UserVisitorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户访客Service实现类
 * 重构说明：从UserRelationship拆分出来，专门处理用户访客记录功能
 */
@Service
public class UserVisitorServiceImpl extends ServiceImpl<UserVisitorMapper, UserVisitor> implements UserVisitorService {

    @Resource
    private AchievementService achievementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recordVisit(Long visitorUserId, Long visitedUserId) {
        if (visitorUserId.equals(visitedUserId)) {
            return true; // 访问自己不记录
        }

        // 检查是否已经有访问记录（24小时内）
        LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
        LambdaQueryWrapper<UserVisitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserVisitor::getVisitorId, visitorUserId)
               .eq(UserVisitor::getUserId, visitedUserId)
               .gt(UserVisitor::getLastVisitAt, yesterday);
        
        UserVisitor existing = getOne(wrapper);
        if (existing != null) {
            // 更新访问时间
            existing.setVisitedAt(LocalDateTime.now());
            return updateById(existing);
        }

        // 创建新的访问记录
        UserVisitor visitor = new UserVisitor();
        visitor.setVisitorUserId(visitorUserId);
        visitor.setVisitedUserId(visitedUserId);
        visitor.setVisitedAt(LocalDateTime.now());
        visitor.setCreatedAt(LocalDateTime.now());
        boolean saved = save(visitor);
        
        // 检查访客相关成就
        if (saved) {
            achievementService.checkVisitorAchievements(visitorUserId, true);  // 访问他人
            achievementService.checkVisitorAchievements(visitedUserId, false); // 被访问
        }
        
        return saved;
    }

    @Override
    public List<UserVisitor> getMyVisitors(Long userId, int pageNum, int pageSize) {
        Page<UserVisitor> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UserVisitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserVisitor::getUserId, userId)
               .orderByDesc(UserVisitor::getLastVisitAt);
        
        Page<UserVisitor> result = page(page, wrapper);
        return result.getRecords();
    }
}

